package org.jerry.virtualoperator.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.jerry.virtualoperator.constant.StringConstant;
import org.jerry.virtualoperator.form.VsmsCreateForm;
import org.jerry.virtualoperator.vo.Click;
import org.jerry.virtualoperator.vo.VsmsReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("api/vsms/message")
public class VsmsController {

    @Value("${server.tomcat.basedir}")
    private String basedir;

    static ObjectMapper mapper = new ObjectMapper();
    static XmlMapper xmlMapper = new XmlMapper();


    @PostMapping
    public Click<String> create(@RequestBody @Validated VsmsCreateForm form) throws Exception {
        log.info("receive form: {}", form);
        String id = UUID.randomUUID().toString();
        File dir = new File(basedir + File.separator + StringConstant.MOBILE_FILE_DIR);
        if(!dir.exists()) {
            dir.mkdir();
        }

        File file = new File(dir, id + ".json");
        log.info("file: {}", file.getAbsolutePath());

        try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(mapper.writeValueAsString(form));
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return Click.succ(id);
    }

    @SneakyThrows
    @PostMapping("/reportion")
    public String report(HttpServletRequest request) {
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String body = reader.lines().collect(Collectors.joining());
            log.info("receive report: {}", body);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }


        Thread.sleep(100);
        return "SUCCESS";
    }

}
